package
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.TimerEvent;
	import flash.net.Socket;
	import flash.utils.Timer;

	public class CCUMonitor
	{
		private static var  _pingDelay : int			=	-1;
		private static var _serverAddress : String		=	null;
		private static var _serverPort : int			=	-1;
		private static var _socket : Socket				=	null;
		private static var _timer : Timer				=	null;
		
		public static function start( serverAddress : String = null, serverPort : int = -1, pingDelay : int = -1 ) : void
		{						
			if( serverAddress == null || serverAddress.length == 0 )
				return;
			
			if( serverPort <= 0 )
				return;
			
			if( pingDelay <= 0 )
				return;
			
			_serverAddress	=	serverAddress;
			_serverPort		=	serverPort;			
			_pingDelay		=	pingDelay;
			
			_socket			=	new Socket( serverAddress, serverPort );
			_socket.addEventListener( Event.CONNECT, handleConnect );
			_socket.addEventListener( Event.CLOSE, handleClose );
			_socket.addEventListener( IOErrorEvent.IO_ERROR, handleClose );
			_socket.addEventListener( SecurityErrorEvent.SECURITY_ERROR, handleSecurityError );
			_socket.addEventListener( ProgressEvent.SOCKET_DATA, handleData );			
			
			_timer			=	new Timer( _pingDelay, 0 );
			_timer.addEventListener(TimerEvent.TIMER, handleTimer );
			_timer.start();
		}
		
		///////////////////////////////////////////
		private static function handleTimer( e : Event ) : void
		{
			try
			{
				// Reconnect made ping sinal to host
				_socket.connect( _serverAddress, _serverPort );
			}
			catch( ex : * ){}
		}
		
		private static function handleConnect( e : Event ) : void
		{
			_timer.stop();
		}
		
		private static function handleClose( e : Event ) : void
		{
			_timer.start();
		}
		
		private static function handleSecurityError( e : Event ) : void
		{
			_timer.stop();
		}
		
		private static function handleData( e : Event ) : void
		{
			
		}
	}
}